import React, { useRef, useEffect, useCallback } from "react";
import { debounce } from "lodash";
import ReactDOM from "react-dom/client";
import "./index.less";
import ContentSource from "../ContentSource";
import { parseString } from "@/utils/common";

const md = require("markdown-it")({
  html: true,
  typographer: true,
});

interface IProps {
  chatInfo: {
    msgId: string;
    dataId: string;
  };
  content: string;
  language: AppLanguageType;
  featureData: any;
  onRender?: (isForce?: boolean) => void;
}

interface FeatureItemType {
  type: ChatFeatureType;
  id: string;
  domId: string;
  content: string;
  renderStr: string;
}

const ChatThink: React.FC<IProps> = ({ featureData, content }) => {
  const mdRef = useRef<HTMLDivElement>(null);
  const featureRef = useRef<FeatureItemType[]>([]);
  const echartsId = useRef<number>(0);
  const featureDataRef = useRef<any>(featureData);
  const parseMd = (
    mdStr: string
  ): Promise<{
    resultHtml: string | undefined;
    featureArr: FeatureItemType[];
  }> => {
    return new Promise((reslove) => {
      const result = md.render(mdStr);
      const arr: FeatureItemType[] = [];
      const regex = /%%[^#]+##/g;
      const replacedString = result.replace(
        regex,
        (match: any, openTag: any, content: any, closeTag: any) => {
          echartsId.current += 1;
          const matchText = match.match(/%%([^#]+)##/);
          const textContent = matchText && matchText[1] ? matchText[1] : "";
          const splitArr = textContent.split("-");
          const codeType = splitArr[1];
          const codeId = splitArr[2];
          const resId = codeId || echartsId.current;
          const idStr = `chat-${codeType}-${featureDataRef.current.msgId}-${resId}-${echartsId.current}`;
          const classStr = `chat-${codeType}-block`;
          const replacement = `<span id='${idStr}' class='${classStr}'></span>`;
          arr.push({
            type: codeType,
            id: resId,
            domId: idStr,
            content: textContent,
            renderStr: replacement,
          });
          return replacement;
        }
      );
      reslove({
        resultHtml: replacedString,
        featureArr: arr,
      });
    });
  };
  const renderContentSource = (data: FeatureItemType) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const root = ReactDOM.createRoot(targetDom as HTMLElement);
    const featureData = featureDataRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};

    let rsourceData: any = null;
    if (chartDataCxt[data.id]) {
      const sourceData = chartDataCxt[data.id];
      if (typeof sourceData === "string") {
        const resData = parseString(sourceData);
        if (resData) rsourceData = resData;
      } else {
        rsourceData = sourceData;
      }
    }
    root.render(
      <ContentSource data={data} rsourceData={rsourceData}></ContentSource>
    );
  };
  const renderFeature = () => {
    featureRef.current.forEach((item) => {
      if (item.type === "contentSource") {
        renderContentSource(item);
      }
    });
  };
  const renderFeatureCb = useCallback(
    debounce(() => {
      if (featureRef.current.length > 0) {
        renderFeature();
      }
    }, 1000),
    []
  );
  useEffect(() => {
    parseMd(content).then((res) => {
      if (mdRef.current) {
        mdRef.current.innerHTML = res.resultHtml || "";
      }
      if (res.featureArr.length) {
        featureRef.current = res.featureArr;
        renderFeatureCb();
      }
    });
  }, [content]);
  return <div className="chat-think-content" ref={mdRef}></div>;
};

export default ChatThink;
